#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char *sftp = "/usr/lib/openssh/sftp-server";

void reject(char *err) {
  printf("This is a restricted account.\n"
         "You cannot execute anything here.\n"
         "Goodbye.\n");
  /*  printf("%s\n",err);	 	 */
  /*  printf("guid: %d\nhomedir: %s\n", getuid(), getenv("HOME"));	 */

  exit(89);
}

void chrootsftp(int uid, char *dir) {
  int gidlist[] = {666};
  gidlist[0] = uid;

  chdir(dir);
  chroot(dir);
  setgid(gidlist[0]);
  setgroups(1, gidlist);  // also, could use initgroups
  setuid(gidlist[0]);
  execl(sftp, sftp, NULL);
}

int main(int argc, char*argv[]) {
  if (argc != 3) {
    reject("Only two arguments allowed");
  }

  if (!strstr(argv[1], "-c") && !strstr(argv[1], "-e")) {
    reject("Illegal option");
  }

  if (!strstr(argv[2], "sftp-server")) {
    reject("This shell can only run sftp");
  }

  chrootsftp(getuid(), getenv("HOME"));
}

